"""
数据导出工具
支持导出分析结果到Excel/CSV
"""

import pandas as pd
from datetime import datetime
import os
import logging

from config import current_config as config


class DataExporter:
    """数据导出类"""
    
    def __init__(self):
        self.export_dir = config.EXPORT_DIR
        self._ensure_export_dir()
    
    def _ensure_export_dir(self):
        """确保导出目录存在"""
        if not os.path.exists(self.export_dir):
            os.makedirs(self.export_dir)
            logging.info(f"创建导出目录: {self.export_dir}")
    
    def export_analysis_report(self, stock_code, stock_name, realtime_data, 
                               hist_data, signals, score, recommendation, risk_info):
        """
        导出完整分析报告
        
        参数:
            stock_code: 股票代码
            stock_name: 股票名称
            realtime_data: 实时数据字典
            hist_data: 历史数据DataFrame
            signals: 信号列表
            score: 综合评分
            recommendation: 投资建议元组 (建议, 说明, 类型)
            risk_info: 风险信息字典
        
        返回:
            str: 导出的文件路径
        """
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        filename = f"{stock_code}_{stock_name}_分析报告_{timestamp}.xlsx"
        filepath = os.path.join(self.export_dir, filename)
        
        try:
            with pd.ExcelWriter(filepath, engine='openpyxl') as writer:
                # 1. 基本信息
                basic_info = self._create_basic_info(stock_code, stock_name, realtime_data)
                basic_info.to_excel(writer, sheet_name='基本信息', index=False)
                
                # 2. 量化分析结果
                analysis_result = self._create_analysis_result(score, recommendation, signals)
                analysis_result.to_excel(writer, sheet_name='分析结果', index=False)
                
                # 3. 风险指标
                if risk_info:
                    risk_df = pd.DataFrame([risk_info])
                    risk_df.to_excel(writer, sheet_name='风险分析', index=False)
                
                # 4. 历史数据
                if hist_data is not None and len(hist_data) > 0:
                    hist_data_export = hist_data.tail(100).copy()  # 只导出最近100条
                    hist_data_export.to_excel(writer, sheet_name='历史数据', index=False)
                
                # 5. 技术指标摘要
                if hist_data is not None and len(hist_data) > 0:
                    tech_summary = self._create_technical_summary(hist_data)
                    tech_summary.to_excel(writer, sheet_name='技术指标', index=False)
            
            logging.info(f"分析报告已导出: {filepath}")
            return filepath
        
        except Exception as e:
            logging.error(f"导出分析报告失败: {str(e)}")
            return None
    
    def _create_basic_info(self, stock_code, stock_name, realtime_data):
        """创建基本信息表"""
        data = {
            '项目': ['股票代码', '股票名称', '导出时间'],
            '内容': [stock_code, stock_name, datetime.now().strftime('%Y-%m-%d %H:%M:%S')]
        }
        
        if realtime_data:
            data['项目'].extend([
                '最新价', '涨跌幅', '涨跌额', '开盘价', '最高价', '最低价',
                '成交量(手)', '成交额(元)', '量比', '换手率(%)',
                '市盈率', '市净率', '总市值(元)', '流通市值(元)'
            ])
            data['内容'].extend([
                f"¥{realtime_data['最新价']:.2f}",
                f"{realtime_data['涨跌幅']:.2f}%",
                f"¥{realtime_data['涨跌额']:.2f}",
                f"¥{realtime_data['开盘价']:.2f}",
                f"¥{realtime_data['最高价']:.2f}",
                f"¥{realtime_data['最低价']:.2f}",
                f"{realtime_data['成交量']/100:.0f}",
                f"{realtime_data['成交额']:.0f}",
                f"{realtime_data['量比']:.2f}",
                f"{realtime_data['换手率']:.2f}",
                f"{realtime_data['市盈率']:.2f}",
                f"{realtime_data['市净率']:.2f}",
                f"{realtime_data['总市值']:.0f}",
                f"{realtime_data['流通市值']:.0f}"
            ])
        
        return pd.DataFrame(data)
    
    def _create_analysis_result(self, score, recommendation, signals):
        """创建分析结果表"""
        data = {
            '项目': ['综合评分', '投资建议', '建议说明'],
            '内容': [
                f"{score:.2f} / 100",
                recommendation[0],
                recommendation[1]
            ]
        }
        
        df = pd.DataFrame(data)
        
        # 添加技术信号
        if signals:
            signal_df = pd.DataFrame({
                '项目': ['技术信号'] * len(signals),
                '内容': signals
            })
            df = pd.concat([df, signal_df], ignore_index=True)
        
        return df
    
    def _create_technical_summary(self, hist_data):
        """创建技术指标摘要"""
        latest = hist_data.iloc[-1]
        
        data = []
        
        # 均线
        for period in [5, 10, 20, 60, 120]:
            if f'MA{period}' in latest:
                data.append({
                    '指标类型': '趋势指标',
                    '指标名称': f'MA{period}',
                    '当前值': f"{latest[f'MA{period}']:.2f}" if pd.notna(latest[f'MA{period}']) else '-'
                })
        
        # MACD
        if 'DIF' in latest:
            data.extend([
                {'指标类型': '动量指标', '指标名称': 'DIF', '当前值': f"{latest['DIF']:.2f}"},
                {'指标类型': '动量指标', '指标名称': 'DEA', '当前值': f"{latest['DEA']:.2f}"},
                {'指标类型': '动量指标', '指标名称': 'MACD', '当前值': f"{latest['MACD']:.2f}"}
            ])
        
        # KDJ
        if 'K' in latest:
            data.extend([
                {'指标类型': '动量指标', '指标名称': 'K', '当前值': f"{latest['K']:.2f}"},
                {'指标类型': '动量指标', '指标名称': 'D', '当前值': f"{latest['D']:.2f}"},
                {'指标类型': '动量指标', '指标名称': 'J', '当前值': f"{latest['J']:.2f}"}
            ])
        
        # RSI
        for period in [6, 12, 24]:
            if f'RSI{period}' in latest:
                data.append({
                    '指标类型': '动量指标',
                    '指标名称': f'RSI{period}',
                    '当前值': f"{latest[f'RSI{period}']:.2f}" if pd.notna(latest[f'RSI{period}']) else '-'
                })
        
        # 布林带
        if 'BOLL_UPPER' in latest:
            data.extend([
                {'指标类型': '波动指标', '指标名称': '布林上轨', '当前值': f"{latest['BOLL_UPPER']:.2f}"},
                {'指标类型': '波动指标', '指标名称': '布林中轨', '当前值': f"{latest['BOLL_MID']:.2f}"},
                {'指标类型': '波动指标', '指标名称': '布林下轨', '当前值': f"{latest['BOLL_LOWER']:.2f}"}
            ])
        
        return pd.DataFrame(data)
    
    def export_to_csv(self, data, filename):
        """导出DataFrame到CSV"""
        filepath = os.path.join(self.export_dir, filename)
        try:
            data.to_csv(filepath, index=False, encoding='utf-8-sig')
            logging.info(f"CSV文件已导出: {filepath}")
            return filepath
        except Exception as e:
            logging.error(f"导出CSV失败: {str(e)}")
            return None
    
    def export_multi_stock_comparison(self, comparison_data):
        """导出多股票对比数据"""
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        filename = f"多股票对比_{timestamp}.xlsx"
        filepath = os.path.join(self.export_dir, filename)
        
        try:
            with pd.ExcelWriter(filepath, engine='openpyxl') as writer:
                comparison_data.to_excel(writer, sheet_name='对比结果', index=False)
            
            logging.info(f"对比数据已导出: {filepath}")
            return filepath
        except Exception as e:
            logging.error(f"导出对比数据失败: {str(e)}")
            return None

